package com.yunxin.download.server.infra.support.mgb;

import org.mybatis.generator.api.MyBatisGenerator;
import org.mybatis.generator.api.ProgressCallback;
import org.mybatis.generator.api.VerboseProgressCallback;
import org.mybatis.generator.config.Configuration;
import org.mybatis.generator.config.xml.ConfigurationParser;
import org.mybatis.generator.internal.DefaultShellCallback;

import java.io.InputStream;
import java.util.Arrays;
import java.util.LinkedList;
import java.util.List;
import java.util.Objects;

/**
 * @author zero°
 * @since 2023-05-24
 */
public enum ExtendMybatisGenerator {
    /**
     * 单例
     */
    X;

    /**
     * mybatis生成
     * @param configFile configFile
     * @throws Exception Exception
     */
    public void generate(String configFile) throws Exception {
        if (Objects.nonNull(configFile)) {
            generate(ExtendMybatisGenerator.class.getResourceAsStream(configFile));
        }
    }

    /**
     * mybatis生成
     * @param inputStream inputStream
     * @throws Exception Exception
     */
    public void generate(InputStream inputStream) throws Exception {
        //MBG 执行过程中的警告信息
        List<String> warnings = new LinkedList<>();
        //当生成的代码重复时，覆盖原代码
        boolean overwrite = true;
        ConfigurationParser cp = new ConfigurationParser(warnings);
        Configuration config = cp.parseConfiguration(inputStream);
        inputStream.close();
        DefaultShellCallback callback = new DefaultShellCallback(overwrite);
        MyBatisGenerator myBatisGenerator = new MyBatisGenerator(config, callback, warnings);
        ProgressCallback progressCallback = new VerboseProgressCallback();
        myBatisGenerator.generate(progressCallback);
        System.out.println(Arrays.toString(warnings.toArray()));
    }

}
